package com.swpu;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@WebServlet(urlPatterns = "/hello",initParams = {@WebInitParam(name = "name", value = "swpu")})
public class HelloServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("this is doGet");getParams(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("this is doPost");
        getParams(request,response);
    }
    private void getParams(HttpServletRequest request, HttpServletResponse response) throws IOException{
//        获取ServeltConfig对象，并获取参数
        ServletConfig config = this.getServletConfig();
        String name = config.getInitParameter("name");
//        //设置中文乱码1
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("content-type","text/html;charset=UTF-8");
        //设置中文乱码2
        response.setContentType("text/html;charset=UTF-8");

        //将数据打印在网页上
        String msg = "西南石油大学";
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(msg.getBytes());

        response.sendRedirect("/3_9javaweb/first");

    }
}
